package cn.tedu.crm.base.config;


import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebMvc 配置类
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>();
        bean.setOrder(0);
        bean.setFilter(new CorsFilter(source));
        return bean;
    }
    //    @Override
    //    public void addCorsMappings(CorsRegistry registry) {
    //        registry.addMapping("/**")
    //                .allowedOriginPatterns("*")
    //                .allowedMethods("*")
    //                .allowedHeaders("*")
    //                .allowCredentials(true)
    //                .maxAge(3600);
    //    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 在此处注册自定义拦截器
        registry.addInterceptor(new SaInterceptor(auth -> {
                    StpUtil.checkLogin();
                    System.out.println("SaInterceptor...");
                }))
                .addPathPatterns("/api/**")
                .excludePathPatterns(
                        "/api/captcha",
                        "/api/sms/send",
                        "/api/crm/user/login",
                        "/api/file/upload/**",
                        "/api/crm/img/**"
                );
    }

}
